/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { defineComponent, ref, nextTick, h, PropType } from 'vue'
import { NButton, NInput } from 'naive-ui'
import { EditOutlined } from '@vicons/antd'

const props = {
  value: {
    type: String as PropType<string>,
    default: ''
  },
  updateEdit: {
    type: Function as PropType<(v: any) => void>,
    default: () => {}
  }
}

const ShowEdit = defineComponent({
  name: 'ShowEdit',
  props,
  setup(props) {
    const { updateEdit } = props
    const isEdit = ref(false)
    const inputRef = ref(null)
    const inputValue = ref(props.value)
    function handleOnClick() {
      isEdit.value = true
      nextTick(() => {
        ;(inputRef.value as any).focus()
      })
    }
    function handleChange() {
      updateEdit(inputValue.value)
      isEdit.value = false
    }
    return () =>
      h(
        'div',
        {
          onClick: handleOnClick
        },
        isEdit.value
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value,
              onUpdateValue: (v) => {
                inputValue.value = v
              },
              onBlur: handleChange
            })
          : h(
              'div',
              {
                style:
                  'display: flex; flex-direction: row; justify-content: space-between;'
              },
              [
                h('span', props.value),
                h(
                  NButton,
                  {
                    circle: true,
                    ghost: true,
                    bordered: false,
                    size: 'tiny',
                    type: 'info',
                    onClick: () => {
                      handleOnClick()
                    }
                  },
                  {
                    icon: () => h(EditOutlined)
                  }
                )
              ]
            )
      )
  }
})

export default ShowEdit
